
package com.yimixian.app.util;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.tencent.mm.sdk.modelmsg.GetMessageFromWX;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.common.Constants;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class WeChatUtils {
    public static final int WE_CHAT_SHARE_REST = 0;
    public static final int WE_CHAT_SHARE_SUCCESS = 1;
    public static final int WE_CHAT_SHARE_FAIL = -1;

    private static WeChatUtils mWeChatUtils;

    public enum ShareType {
        WECHAT_FRIEND, WECHAT_CIRCLE
    }

    private WeChatUtils() {

    }

    public static WeChatUtils getInstance() {
        if (mWeChatUtils == null) {
            mWeChatUtils = new WeChatUtils();
        }
        return mWeChatUtils;
    }

    public void sendWeChatMessage(final Context context, Uri uri, final ShareType shareType) {
        final IWXAPI wxapi = WXAPIFactory.createWXAPI(context, Constants.WECHAT_APP_ID, false);
        wxapi.registerApp(Constants.WECHAT_APP_ID);
        WXWebpageObject webpage = new WXWebpageObject();
        String url = uri.getQueryParameter("link");
        try {
            webpage.webpageUrl = URLDecoder.decode(url,"utf-8");// 可以为空
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final WXMediaMessage wxMediaMessage = new WXMediaMessage(webpage);

        String shareTitle = uri.getQueryParameter("title");
        wxMediaMessage.title = TextUtils.isEmpty(shareTitle) ? "一米鲜优惠" : shareTitle;
        wxMediaMessage.description = uri.getQueryParameter("description"); // 可以为空
        String shareIcon = uri.getQueryParameter("icon");
        if (TextUtils.isEmpty(shareIcon)) {
            wxMediaMessage.thumbData = bitmapToByteArray(
                    BitmapFactory.decodeResource(context.getResources(),
                            R.drawable.push),
                    true);
            share(wxapi, wxMediaMessage, shareType);
        } else {
            Target mTarget = new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    Log.e("WechatUtils","onBitmapLoaded--------========");
                    wxMediaMessage.thumbData = bitmapToByteArray(bitmap, false);
                    Log.e("WechatUtils", "onBitmapLoaded--------");
                    share(wxapi, wxMediaMessage, shareType);
                    Log.e("WechatUtils", "onBitmapLoaded========");
                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                    wxMediaMessage.thumbData = bitmapToByteArray(BitmapFactory.decodeResource(
                            context.getResources(), R.drawable.push), true);
                    share(wxapi, wxMediaMessage, shareType);
                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                }
            };
            Picasso.with(context).load(shareIcon).resize(120, 120).into(mTarget);
        }

    }

    public void shareImage(Context context,Bitmap bitmap,final ShareType shareType) {
        if(context == null && bitmap == null) {
            return ;
        }
        final IWXAPI wxapi = WXAPIFactory.createWXAPI(context, Constants.WECHAT_APP_ID, false);
        wxapi.registerApp(Constants.WECHAT_APP_ID);
        WXImageObject imgObj = new WXImageObject(bitmap);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
//        bmp.recycle();
        msg.thumbData = bitmapToByteArray(thumbBmp, true);  // 设置缩略图

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "img" + System.currentTimeMillis();
        req.message = msg;
        req.scene = shareType.equals(ShareType.WECHAT_FRIEND) ? SendMessageToWX.Req.WXSceneSession
            : SendMessageToWX.Req.WXSceneTimeline;
        wxapi.sendReq(req);
    }

    private void share(IWXAPI iwxapi, WXMediaMessage msg, ShareType shareType) {
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage" + System.currentTimeMillis();
        req.message = msg;
        req.scene = shareType.equals(ShareType.WECHAT_FRIEND) ? SendMessageToWX.Req.WXSceneSession
                : SendMessageToWX.Req.WXSceneTimeline;
        iwxapi.sendReq(req);
    }

    public byte[] bitmapToByteArray(final Bitmap bitmap, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bitmap.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static void share2weixin(String url, String title, String description, String iconUrl,
            final ShareType shareType) {
        final IWXAPI wxapi = WXAPIFactory.createWXAPI(SystemFramework.getInstance()
                .getGlobalContext(), Constants.WECHAT_APP_ID, false);
        wxapi.registerApp(Constants.WECHAT_APP_ID);
        if (!wxapi.isWXAppInstalled()) {
            UiUtils.showToast(SystemFramework.getInstance().getGlobalContext()
                    .getString(R.string.no_wechat_app));
            return;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = description;
        Picasso.with(SystemFramework.getInstance().getGlobalContext()).load(iconUrl)
                .into(new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        Bitmap thumb = bitmap;
                        msg.setThumbImage(thumb);
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = String.valueOf(System.currentTimeMillis());
                        req.message = msg;
                        req.scene = shareType.equals(ShareType.WECHAT_FRIEND) ? SendMessageToWX.Req.WXSceneSession
                            : SendMessageToWX.Req.WXSceneTimeline;
                        wxapi.sendReq(req);
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {
                        Bitmap thumb = BitmapFactory.decodeResource(SystemFramework.getInstance()
                             .getGlobalContext().getResources(),
                             R.drawable.push);
                        msg.setThumbImage(thumb);
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = String.valueOf(System.currentTimeMillis());
                        req.message = msg;
                        req.scene = shareType.equals(ShareType.WECHAT_FRIEND) ? SendMessageToWX.Req.WXSceneSession
                            : SendMessageToWX.Req.WXSceneTimeline;
                        wxapi.sendReq(req);
                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }
                });
    }

}
